package com.leyou.item.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.pojo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    /**
     * 品牌管理页,分页展示
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, boolean desc, String key) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key.toUpperCase());
        }
        if (StringUtils.isNotBlank(sortBy)) {
            // 排序
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        Page<Brand> brandPage = (Page<Brand>) brandMapper.selectByExample(example);
        return new PageResult<>(brandPage.getTotal(),new Long(brandPage.getPages()), brandPage.getResult());

    }


    /**
     * 新增品牌,添加品牌分类
     * @param cids
     * @param brand
     */
    @Transactional
    public void saveBrand(List<Long> cids, Brand brand) {
        //添加品牌
        this.brandMapper.insertSelective(brand);
        //添加品牌分类
        cids.forEach(cid-> this.brandMapper.insertCategoryBrand(cid, brand.getId()));
    }


    /**
     * 品牌管理,分页展示  根据brand_id 查询品牌名称
     * @param brandId
     * @return
     */
    public String queryNameById(Long brandId) {
        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);
        return brand.getName();
    }


    /**
     *商品管理新增/修改页面 所属品牌 数据回显
     * @param cid
     * @return
     */
    public List<Brand> queryBrandByCategory(Long cid) {
        return this.brandMapper.queryBrandByCategoryId(cid);
    }


    /**
     * 品牌管理界面,根据bid删除品牌
     * @param bid  brand_id
     */
    public void deleteByBrandId(Long bid) {

        this.brandMapper.deleteBrandCategroyByBid(bid);

        this.brandMapper.deleteByPrimaryKey(bid);
    }

    public List<Brand> queryBrandByBids(List<Long> bids) {
        return this.brandMapper.selectByIdList(bids);
    }
}
